#include "app_com.h"
#include "sys/time.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "log.h"

long app_com_getcurtime_ms(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
}

char *app_com_bytes2hexstr(char *bytes, int len)
{
    char *hexstr = (char *)malloc(len * 2 + 1);
    for (int i = 0; i < len; i++)
    {
        sprintf(hexstr + i * 2, "%02x", bytes[i]);
    }
    hexstr[len * 2] = '\0';
    return hexstr;
}

int app_com_hexstr2bytes(char *hexstr, char *data, int data_len)
{
    int len = strlen(hexstr) / 2; // 字节数组的长度
    if (len > data_len)
    {
        log_error("hexstr too long"); // hexstr长度超过字节数组最大的长度
    }
    for (size_t i = 0; i < strlen(hexstr); i += 2)
    {
        sscanf(hexstr + i, "%2hhx", &data[i / 2]);
    }
    return len;
}
